//
//  XMPointsViewController.m
//  XunMi
//
//  Created by MacBook on 2024/3/14.
//  Copyright © 2024 TieZhu. All rights reserved.
//

#import "XMPointsViewController.h"
#import "XMPointsHeaderView.h"
#import "XMPointsTableViewCell.h"
#import "XMPointsListViewController.h"
#import "XMPointsBindViewController.h"
#import "XMPointsModel.h"
#import "XMRealTipView.h"
#import "XMRealViewController.h"
#import "XMWithdrawListViewController.h"
#import "XMPointsUseCardView.h"
#import "XMPointsCollectionViewCell.h"
#import "XMLoginPrivacyTipView.h"
#import "XMPointsFrozenView.h"

@interface XMPointsViewController () <UICollectionViewDelegate, UICollectionViewDataSource>
@property (nonatomic, strong) XMPointsHeaderView *headerView;
@property (nonatomic, strong) XMUserModel *model;
@property (nonatomic, strong) NSMutableArray <XMPointsModel *> *dataArray;
@property (nonatomic, strong) XMRealTipView *realTipView;
@property (nonatomic, strong) XMPointsUseCardView *cardView;

@property (nonatomic, strong) UIView *cBgView;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) XMPointsModel *selModel;
@property (nonatomic, strong) XMLoginPrivacyTipView *tipView;
@property (nonatomic, strong) XMPointsFrozenView *frozenView;
@end

@implementation XMPointsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupSubviews];
    [self userInfo];
    [self listData];
    [self viewBlock];
}

#pragma mark - initData
- (void)userInfo {
    NSMutableDictionary *dic = @{
        @"module": @"6"
    }.mutableCopy;
    [YHNetworkManager.sharedInstance postWithUrl:@"api/user/obtain" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
        if (tip.success) {
            self.model = [XMUserModel mj_objectWithKeyValues:result];
            self.headerView.model = self.model;
            self.headerView.tipImgV.hidden = self.model.frozen_score.intValue == 0;
            if (self.model.frozen_score.intValue > 0) {
                NSString *text = kStringFormat(@"亲爱的用户，您好！\n由于您的违规操作导致本次冻结了%@ 积分，如果您对处理结果不满意，可以联系客服申诉，感谢您的配合！", self.model.frozen_score);
                // 创建NSMutableAttributedString，并设置文本内容和属性
                NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:text];
                // 创建NSMutableParagraphStyle，并设置行高
                NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
                paragraphStyle.lineSpacing = 8; // 设置行高为10个点
                // 将行高属性添加到文本属性中
                [attributedText addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, attributedText.length)];
                self.frozenView.tipLa.attributedText = attributedText;
                [self.frozenView.tipLa sizeToFit]; // 自适应文本内容的大小
            }
            
            if (self.model.coupon_number.intValue == 0) {
                self.cardView.hidden = YES;
                self.cardView.selBtn.selected = NO;
                [self.cBgView mas_remakeConstraints:^(MASConstraintMaker *make) {
                    make.top.mas_equalTo(self.headerView.mas_bottom).offset(16);
                    make.left.equalTo(self.view).offset(20);
                    make.right.equalTo(self.view).offset(-20);
                }];
            } else {
                self.cardView.hidden = NO;
                self.cardView.selBtn.selected = YES;
                
                NSString *str = kStringFormat(@"%@张", self.model.coupon_number);
                NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:str];
                [attrStr addAttributes:@{NSFontAttributeName: kUIFontBold(21)} range:[str rangeOfString:self.model.coupon_number]];
                [attrStr addAttributes:@{NSFontAttributeName: kUIFontBold(12)} range:[str rangeOfString:@"张"]];
                self.cardView.countLa.attributedText = attrStr;
                
                [self.cardView mas_remakeConstraints:^(MASConstraintMaker *make) {
                    make.top.mas_equalTo(self.headerView.mas_bottom).offset(16);
                    make.left.equalTo(self.view).offset(20);
                    make.right.equalTo(self.view).offset(-20);
                    make.height.mas_offset(48);
                }];
                [self.cBgView mas_remakeConstraints:^(MASConstraintMaker *make) {
                    make.top.mas_equalTo(self.headerView.mas_bottom).offset(80);
                    make.left.equalTo(self.view).offset(20);
                    make.right.equalTo(self.view).offset(-20);
                }];
            }
        }
    }];
}

- (void)listData {
    [MBProgressHUD showHUDActivityMsg:nil toView:kWindow];
    NSMutableDictionary *dic = @{
    }.mutableCopy;
    
    [YHNetworkManager.sharedInstance postWithUrl:@"api/config/withdrawalList" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
        if (tip.success) {
            [MBProgressHUD hideHUD];
            self.dataArray = [NSMutableArray arrayWithArray:[XMPointsModel mj_objectArrayWithKeyValuesArray:result[@"record"]]];
            
            double number = self.dataArray.count / 2.0;
            double roundedNumber = ceil(number);
            NSLog(@"Rounded number: %f", roundedNumber);
            CGFloat cH = roundedNumber * 60 + (roundedNumber - 1) * 10;
            [self.collectionView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(self.cBgView).offset(47);
                make.left.equalTo(self.cBgView).offset(18);
                make.right.equalTo(self.cBgView).offset(-18);
                make.height.mas_offset(cH);
                make.bottom.equalTo(self.cBgView).offset(-20);
            }];
            [self.collectionView reloadData];
        }
    }];
}

#pragma mark - setupSubViews
- (void)setupSubviews {
    self.navView.backgroundColor = kHEX(@"#F2F2F2");
    self.view.backgroundColor = kHEX(@"#F2F2F2");
    [self.navLeft2Btn setTitle:@"我的积分" forState:UIControlStateNormal];
    [self.navRightBtn setTitle:@"提现记录" forState:UIControlStateNormal];
    [self.navRightBtn addTarget:self action:@selector(withdrawDetail) forControlEvents:UIControlEventTouchUpInside];
    
    _headerView = [XMPointsHeaderView viewFromXib];
    
    [self.view addSubview:_headerView];
    [_headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.navView.mas_bottom).offset(4);
        make.left.equalTo(self.view).offset(0);
        make.right.equalTo(self.view).offset(0);
        make.height.mas_offset(223);
    }];
    
    self.cardView = [XMPointsUseCardView viewFromXib];
    [self.view addSubview:self.cardView];
    
    _cBgView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.view addSubview:_cBgView];
    [self.cBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.headerView.mas_bottom).offset(80);
        make.left.equalTo(self.view).offset(20);
        make.right.equalTo(self.view).offset(-20);
    }];
    
    _cBgView.backgroundColor = UIColor.whiteColor;
    kCornerRadius(_cBgView, 10, 0, UIColor.clearColor);
    UILabel *la = [[UILabel alloc] init];
    la.text = @"选择要兑换的积分：";
    la.textColor = k1F1F1F;
    la.font = kUIFontBold(15);
    [self.cBgView addSubview:la];
    
    [la mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.cBgView).offset(14);
        make.left.equalTo(self.cBgView).offset(18);
    }];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake((kScreenWidth - 96) / 3, 60);
    layout.minimumLineSpacing = 10;
    layout.minimumInteritemSpacing = 10;
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerNib:kNibWithName(kStringFromClass(XMPointsCollectionViewCell)) forCellWithReuseIdentifier:kStringFromClass(XMPointsCollectionViewCell)];
    [self.cBgView addSubview:_collectionView];
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(la.mas_bottom).offset(14);
        make.left.equalTo(self.cBgView).offset(18);
        make.right.equalTo(self.cBgView).offset(-18);
        make.height.mas_offset(200);
        make.bottom.equalTo(self.cBgView).offset(-20);
    }];
    
    UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [button setBackgroundImage:kGetImage(@"points_btn") forState:UIControlStateNormal];
    [button setTitle:@"立即提现" forState:UIControlStateNormal];
    button.titleLabel.font = kUIFontBold(16);
    [button addTarget:self action:@selector(tixian) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:button];
    
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.cBgView.mas_bottom).offset(24);
        make.size.mas_equalTo(CGSizeMake(315, 48));
        make.centerX.equalTo(self.view);
    }];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    XMPointsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kStringFromClass(XMPointsCollectionViewCell) forIndexPath:indexPath];
    cell.model = self.dataArray[indexPath.item];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [self.dataArray enumerateObjectsUsingBlock:^(XMPointsModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (indexPath.item == idx) {
            obj.selected = YES;
            self.selModel = obj;
        } else {
            obj.selected = NO;
        }
    }];
    
    [self.collectionView reloadData];
}

- (void)tixian {
    if (![self isReal]) {
        return;
    }
    if (!self.selModel) {
        [MBProgressHUD showHUDMsg:@"请选择要兑换的积分" toView:kWindow];
        return;
    }
    
    [self.tipView setupWithdrawContent:kStringFormat(@"是否提现%@元,需消耗%@积分", self.selModel.amount, self.selModel.score)];
    
    [GKCover coverFrom:self.view contentView:self.tipView style:(GKCoverStyleTranslucent) showStyle:(GKCoverShowStyleCenter) showAnimStyle:(GKCoverShowAnimStyleNone) hideAnimStyle:(GKCoverHideAnimStyleNone) notClick:YES];
    
    XMWeakSelf(self);
    [self.tipView tipViewLeftBlock:^{
        [GKCover hideCover];
    } rightBlock:^{
        XMStrongSelf(self);
        XMWeakSelf(self);
        [GKCover hideCoverWithHideBlock:^{
            XMStrongSelf(self);
            [MBProgressHUD showHUDActivityMsg:nil  toView:kWindow];
            NSMutableDictionary *dic = @{
                @"index": self.selModel.index,
                @"deduct": @(self.cardView.selBtn.selected ? 1 : 0)
            }.mutableCopy;
            
            [YHNetworkManager.sharedInstance postWithUrl:@"api/money/initiateWithdrawal" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
                if (tip.success) {
                    [MBProgressHUD hideHUD];
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提现申请成功,请等待审核!" message:nil preferredStyle:UIAlertControllerStyleAlert];
                    
                    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault
                                                                          handler:^(UIAlertAction * action) {
                        [self userInfo];
                        [self listData];
                    }];
                    
                    [alert addAction:defaultAction];
                    [self presentViewController:alert animated:YES completion:nil];
                }
            }];
        }];
    }];
    
    
    
}

#pragma mark - viewBlock
- (void)viewBlock {
    XMWeakSelf(self);
    self.headerView.bindBlock = ^{
        XMStrongSelf(self);
        if (![self isReal]) {
            return;
        }
        
        XMPointsBindViewController *vc = [[XMPointsBindViewController alloc] initWithNibName:kStringFromClass(XMPointsBindViewController) bundle:nil];
        [self.navigationController pushViewController:vc animated:YES];
        
        XMWeakSelf(self);
        vc.backBlock = ^{
            XMStrongSelf(self);
            [self userInfo];
        };
    };
    
    self.headerView.detailBlock = ^{
        XMStrongSelf(self);
        XMPointsListViewController *vc = [[XMPointsListViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    };
    
    self.headerView.froBlock = ^{
        XMStrongSelf(self);
        if (self.model.frozen_score.intValue > 0) {
            [GKCover coverFrom:self.view contentView:self.frozenView style:(GKCoverStyleTranslucent) showStyle:(GKCoverShowStyleCenter) showAnimStyle:(GKCoverShowAnimStyleNone) hideAnimStyle:(GKCoverHideAnimStyleNone) notClick:YES];
        }
    };
    
    self.realTipView.closeBlock = ^{
        [GKCover hideCover];
    };
    
    self.realTipView.realBlock = ^{
        XMStrongSelf(self);
        XMWeakSelf(self);
        [GKCover hideCoverWithHideBlock:^{
            XMStrongSelf(self);
            XMRealViewController *vc = [[XMRealViewController alloc] initWithNibName:kStringFromClass(XMRealViewController) bundle:nil];
            [self.navigationController pushViewController:vc animated:YES];
        }];
    };
}

- (BOOL)isReal {
    if (kUserModel.idcard_verify) {
        return YES;
    } else {
        [self showRealTipView];
        return NO;
    }
}

#pragma mark - Actions
- (void)withdrawDetail {
    XMWithdrawListViewController *vc = [[XMWithdrawListViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (XMRealTipView *)realTipView {
    if (!_realTipView) {
        _realTipView = [XMRealTipView viewFromXib];
        _realTipView.size = CGSizeMake(kScreenWidth, kScreenHeight);
    }
    return _realTipView;
}

- (void)showRealTipView {
    [GKCover coverFrom:self.view contentView:self.realTipView style:(GKCoverStyleTranslucent) showStyle:(GKCoverShowStyleCenter) showAnimStyle:(GKCoverShowAnimStyleNone) hideAnimStyle:(GKCoverHideAnimStyleNone) notClick:YES];
}

- (XMLoginPrivacyTipView *)tipView {
    if (_tipView == nil) {
        _tipView = [XMLoginPrivacyTipView viewFromXib];
        _tipView.size = CGSizeMake(295, 177);
    }
    return _tipView;
}

- (XMPointsFrozenView *)frozenView {
    if (_frozenView == nil) {
        _frozenView = [XMPointsFrozenView viewFromXib];
        _frozenView.size = CGSizeMake(kScreenWidth, kScreenHeight);
    }
    return _frozenView;
}

@end
